package com.java.common.boot.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.data.util.CastUtils;

import com.alibaba.fastjson.JSON;

/**
 * 自定义类型处理器JsonTypeHandler
 * 
 * @author yilabao
 * @date 2021年3月8日
 */
public class JsonTypeHandler<T> implements TypeHandler<T> {

    private Class<T> type;

    public JsonTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        // 拿到xml中配置的javaType
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parseJsonString(parameter));
    }

    @Override
    public T getResult(ResultSet rs, String columnName) throws SQLException {
        return parseJavaObject(rs.getString(columnName));
    }

    @Override
    public T getResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJavaObject(rs.getString(columnIndex));
    }

    @Override
    public T getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJavaObject(cs.getString(columnIndex));
    }

    private String parseJsonString(T parameter) {
        if (parameter == null) {
            return null;
        }
        return JSON.toJSONString(parameter);
    }

    private T parseJavaObject(String parameter) {
        if (parameter == null) {
            return null;
        }
        final String jsonArrayPrefix = "[";
        if (parameter.startsWith(jsonArrayPrefix)) {
            return CastUtils.cast(JSON.parseArray(parameter, this.type));
        }
        return JSON.parseObject(parameter, this.type);
    }

}
